<template>
  <div>
    <h3>用户列表页面</h3>
    <a-card>
      <a-row :gutter="20">
        <a-col :span="6">
          <a-input-search v-model="queryParam.username"  allowClear @search="searchUser" placeholder="输入用户名查找" enterButton></a-input-search>
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="addUserVisible = true">新增</a-button>
        </a-col>
      </a-row>
      <a-table
      rowKey="ID"
      :columns="columns"
      :pagination='paginationOption'
      :dataSource="userlist"
       bordered
       @change="handleTableChange"
       >
        <span slot="role" slot-scope="role">{{ role === 1 ? '管理员':'订阅者'}}</span>
        <template slot="action" slot-scope="data">
          <div class="actionSlot">
             <a-button type="primary" icon="edit" style="margin-right:15px" @click="editUser(data.ID)">编辑</a-button>
             <a-button type="danger" icon="delete" style="margin-right:15px" @click="deleteUser(data.ID)">删除</a-button>
             <a-button type="info" icon="info" @click="ChangePassword(data.ID)">修改密码</a-button>
        </div>
      </template>
      </a-table>
    </a-card>
    <!-- 新增用户区域 :config-loading="confirmLoading"-->
    <a-modal width="60%" closable title="新增用户" :visible="addUserVisible"  @ok="addUserOK" @cancel="addUserCancel" destroyOnClose>
      <a-form-model :model="newUser" :rules="addUserRules" ref="addUserRef">
        <a-form-model-item has-feedback label="用户名" prop="username">
          <a-input v-model="newUser.username"></a-input>
        </a-form-model-item>
        <a-form-model-item has-feedback label="密码" prop="password">
          <a-input-password v-model="newUser.password">
          </a-input-password>
        </a-form-model-item>
        <a-form-model-item has-feedback label="确认密码" prop="checkpass">
          <a-input-password v-model="newUser.checkpass">
          </a-input-password>
        </a-form-model-item>
        <a-form-model-item label="是否为管理员" prop="role">
          <a-select defaultValue="2" @change="adminChange">
            <a-select-option key="1" value="1">是</a-select-option>
            <a-select-option key="2 " value="2">否</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 编辑用户区域 -->
    <a-modal width="60%" closable title="编辑用户" :visible="editUserVisible"  @ok="editUserOK" @cancel="editUserCancel" destroyOnClose>
      <a-form-model :model="userInfo" :rules="userRules" ref="addUserRef">
        <a-form-model-item label="用户名" prop="username">
          <a-input v-model="userInfo.username"></a-input>
        </a-form-model-item>
        <a-form-model-item label="是否为管理员">
          <a-switch
            :checked="IsAdmin"
            checked-children="是"
            un-checked-children="否"
            @change="adminChange"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  <!-- 修改密码区域 -->
    <a-modal width="60%" closable title="修改密码" :visible="changePasswordVisible"  @ok="changePasswordOk" @cancel="changePasswordCancel" destroyOnClose>
      <a-form-model :model="changePassword" :rules="changePasswordRules" ref="changePasswordRef">
        <a-form-model-item has-feedback label="密码" prop="password">
          <a-input-password v-model="changePassword.password">
          </a-input-password>
        </a-form-model-item>
        <a-form-model-item has-feedback label="确认密码" prop="checkpass">
          <a-input-password v-model="changePassword.checkpass">
          </a-input-password>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>

const columns = [
  {
    title: 'ID',
    dataIndex: 'ID',
    width: '10%',
    key: 'id',
    align: 'center'
  },
  {
    title: '用户名',
    dataIndex: 'username',
    width: '20%',
    key: 'username',
    align: 'center'
  }, {
    title: '角色',
    dataIndex: 'role',
    width: '20%',
    key: 'role',
    align: 'center',
    scopedSlots: { customRender: 'role' }
  }, {
    title: '操作',
    width: '30%',
    key: 'action',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  data () {
    return {
      paginationOption: {
        pageSizeOptions: ['5', '10', '20'],
        pageSize: 5,
        total: 0,
        showSizeChanger: true,
        showTotal: (total) => `共${total}条`
      },
      userlist: [],
      columns,
      queryParam: {
        username: '',
        pagesize: 5,
        pagenum: 1
      },
      userInfo: {
        id: 0,
        username: '',
        password: '',
        checkpass: '',
        role: 2
      },
      newUser: {
        username: '',
        password: '',
        checkpass: '',
        role: 2
      },
      changePassword: {
        id: 0,
        password: '',
        checkpass: ''
      },
      visible: false,
      addUserVisible: false,
      userRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 4, max: 12, message: '用户名应当在4到12个字符之间', trigger: 'blur' }],
        password: [{
          validator: (rule, value, callback) => {
            if (this.userInfo.password === '') {
              callback(new Error('请输入密码'))
            }
            if ([...this.userInfo.password].length < 6 || [...this.userInfo.password].length > 20) {
              callback(new Error('密码长度为6到20之间'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        checkpass: [{
          validator: (rule, value, callback) => {
            if (this.userInfo.checkpass === '') {
              callback(new Error('请输入密码'))
            }
            if (this.userInfo.password !== this.userInfo.checkpass) {
              callback(new Error('密码不一致，请重新输入'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }]
      },
      addUserRules: {
        username: [
          {
            validator: (rule, value, callback) => {
              if (this.newUser.username === '') {
                callback(new Error('请输入用户名'))
              }
              if ([...this.newUser.username].length < 4 || [...this.newUser.username].length > 12) {
                callback(new Error('用户名应当在4到12个字符之间'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        password: [
          {
            validator: (rule, value, callback) => {
              if (this.newUser.password === '') {
                callback(new Error('请输入密码'))
              }
              if ([...this.newUser.password].length < 6 || [...this.newUser.password].length > 20) {
                callback(new Error('密码应当在6到20位之间'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        checkpass: [
          {
            validator: (rule, value, callback) => {
              if (this.newUser.checkpass === '') {
                callback(new Error('请输入密码'))
              }
              if (this.newUser.password !== this.newUser.checkpass) {
                callback(new Error('密码不一致，请重新输入'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      editUserVisible: false,
      changePasswordVisible: false,
      changePasswordRules: {
        password: [{
          validator: (rule, value, callback) => {
            if (this.changePassword.password === '') {
              callback(new Error('请输入密码'))
            }
            if ([...this.changePassword.password].length < 6 || [...this.changePassword.password].length > 20) {
              callback(new Error('密码长度为6到20之间'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        checkpass: [
          {
            validator: (rule, value, callback) => {
              if (this.changePassword.checkpass === '') {
                callback(new Error('请输入密码'))
              }
              if (this.changePassword.password !== this.changePassword.checkpass) {
                callback(new Error('密码不一致，请重新输入'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  computed: {
    IsAdmin: function () {
      if (this.userInfo.role === 1) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    async getUserList () {
      console.log(this.paginationOption)
      const { data: res } = await this.$http.get('users', {
        params: {
          username: this.queryParam.username,
          pagesize: this.queryParam.pagesize,
          pagenum: this.queryParam.pagenum
        }
      })
      console.log(res)
      if (res.status !== 200) {
        return this.$message.error(res.message)
      } else {
        this.userlist = res.data
        this.paginationOption.total = res.total
      }
    },
    // 搜索用户
    async searchUser () {
      this.queryParam.pagenum = 1
      this.queryParam.current = 1
      const { data: res } = await this.$http.get('users', {
        params: {
          username: this.queryParam.username,
          pagesize: this.queryParam.pagesize,
          pagenum: this.queryParam.pagenum
        }
      })
      if (res.status !== 200) return this.$message.error(res.message)
      this.userlist = res.data
      this.paginationOption.total = res.total
    },
    // 更改分页
    handleTableChange (paginationOption, filters, sorter) {
      var pager = { ...this.pageSizeOptions }
      pager.current = paginationOption.current
      pager.pageSize = paginationOption.pageSize
      this.queryParam.pageSize = paginationOption.pageSize
      this.queryParam.pagenum = paginationOption.current
      if (paginationOption.pageSize !== this.paginationOption.pageSize) {
        this.queryParam.pagenum = 1
        pager.current = 1
      }
      this.paginationOption = pager
      this.getUserList()
    },
    // 删除用户
    deleteUser (id) {
      this.$confirm({
        title: '提示：请再次确认',
        content: '确定要删除该用户吗？一旦删除，无法恢复',
        onOk: async () => {
          const { data: res } = await this.$http.delete(`users/${id}`)
          console.log(res)
          if (res.status !== 200) return this.$message.error(res.message)
          this.$message.success('删除成功')
          this.getUserList()
        },
        onCancel: () => {
          this.$message.info('已取消删除')
        }
      })
    },
    addUserOK () {
      this.$refs.addUserRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('参数不符合要求，请重新输入')
        } else {
          const { data: res } = await this.$http.post('user/add', {
            username: this.newUser.username,
            password: this.newUser.password,
            role: this.newUser.role
          })
          if (res.status !== 200) {
            this.$message.error(res.message)
          } else {
            this.$message.success('添加用户成功')
            this.addUserVisible = false
            this.getUserList()
          }
        }
      })
    },
    addUserCancel () {
      this.$refs.addUserRef.resetFields()
      this.addUserVisible = false
    },
    adminChange (vaule) {
      this.userInfo.role = Number(vaule)
    },
    // 编辑用户
    async editUser (id) {
      this.editUserVisible = true
      const { data: res } = await this.$http.get(`user/${id}`)
      this.userInfo = res.data
      this.userInfo.id = id
    },
    editUserOK () {
      this.$refs.addUserRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('参数不符合要求，请重新输入')
        } else {
          const { data: res } = await this.$http.put(`user/${this.userInfo.id}`, {
            username: this.userInfo.username,
            role: this.userInfo.role
          })
          if (res.status !== 200) {
            this.$message.error(res.message)
          } else {
            this.editUserVisible = false
            this.$message.success('更新用户信息成功')
            this.getUserList()
          }
        }
      })
    },
    editUserCancel () {
      this.$refs.addUserRef.resetFields()
      this.editUserVisible = false
      this.$message.info('编辑已取消')
    },
    async ChangePassword (id) {
      this.changePasswordVisible = true
      const { data: res } = await this.$http.get(`user/${id}`)
      this.changePassword.role = res.data.role
      this.changePassword.id = id
    },
    changePasswordOk () {
      this.$refs.changePasswordRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('参数不符合要求，请重新输入')
        } else {
          const { data: res } = await this.$http.put(`admin/changepw/${this.changePassword.id}`, {
            password: this.changePassword.password
          })
          if (res.status !== 200) {
            this.$message.error(res.message)
          } else {
            this.changePasswordVisible = false
            this.$message.success('更新用户信息成功')
            this.getUserList()
          }
        }
      })
    },
    changePasswordCancel () {
      this.$refs.changePasswordRef.resetFields()
      this.changePasswordVisible = false
      this.$message.info('修改已取消')
    }
  }
}
</script>

<style scoped>
.actionSlot{
display: flex;
justify-content: center;
}
</style>
